<template>
  <!-- 新增表单 -->
  <el-dialog title="新增产品表"
             :visible.sync="visible">
    <el-form class="form">
      <el-form-item label="产品图片"
                    :label-width="formLabelWidth">
        <ImageUpload v-model="formData.productPicture"
                     @setImage="setImage" />
      </el-form-item>
      <el-form-item label="产品名字"
                    :label-width="formLabelWidth">
        <el-input v-model="formData.productName" />
      </el-form-item>
      <el-form-item label="产品价格"
                    :label-width="formLabelWidth">
        <el-input-number v-model="formData.productPrice" />
      </el-form-item>
      <el-form-item label="产品描述"
                    :label-width="formLabelWidth">
        <el-input v-model="formData.productDesc" />
      </el-form-item>
      <el-form-item label="溯源ID"
                    :label-width="formLabelWidth">
        <el-input v-model="formData.traceId" />
      </el-form-item>
    </el-form>
    <div slot="footer"
         class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary"
                 @click="confirm()">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { saveProduct,updateProduct } from "@/api/mall/product";
import ImageUpload from "@/components/Upload/ImageUpload"
export default {
  components: { ImageUpload },
  data () {
    return {
      visible: false,
      formData: {
        productId: '',
        productName: '',
        productDesc: '',
        productPicture: '',
        productPrice: 0,
        traceId: '',
        companyId: ''
      },
      formLabelWidth:"120px"
    }
  },
  methods: {
    init (data) {
      if (data) {
        this.isUpdate = true;
        this.formData = data
      } else {
        this.isUpdate = false;
        this.formData = {
          productId: '',
          productName: '',
          productDesc: '',
          productPicture: '',
          productPrice: 0,
          traceId: '',
          companyId: ''
        }
      }
      this.visible =true;
    },
    setImage (imageUrl) {
      this.formData.productPicture = imageUrl
    },
    confirm () {
      if (this.isUpdate) {
        this.handleConform(updateProduct, this.formData)
      } else {
        this.handleConform(saveProduct, this.formData)
      }
    },
    handleConform (operation) {
      operation(this.formData).then(response => {
        if (response.statusCode == 20000) {
          this.refresh()
          this.visible = false
          this.$message({
            message: '操作成功',
            type: 'success'
          })
        } else {
          this.$message({
            message: '发生错误，操作失败',
            type: 'warning'
          })
        }
      })
    },
    refresh () {
      this.$emit('refresh')
    }
  }
}
</script>
